package cn.ondraw.system.controller.system;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.stp.StpUtil;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
import lombok.RequiredArgsConstructor;
import cn.ondraw.common.core.domain.R;
import cn.ondraw.common.core.validate.AddGroup;
import cn.ondraw.common.core.validate.EditGroup;
import cn.ondraw.common.excel.utils.ExcelUtil;
import cn.ondraw.common.idempotent.annotation.RepeatSubmit;
import cn.ondraw.common.log.annotation.Log;
import cn.ondraw.common.log.enums.BusinessType;
import cn.ondraw.common.mybatis.core.page.PageQuery;
import cn.ondraw.common.mybatis.core.page.TableDataInfo;
import cn.ondraw.common.satoken.utils.LoginHelper;
import cn.ondraw.common.web.core.BaseController;
import cn.ondraw.system.domain.bo.SysModelBo;
import cn.ondraw.system.domain.bo.SysPackagePlanBo;
import cn.ondraw.system.domain.vo.SysModelVo;
import cn.ondraw.system.domain.vo.SysPackagePlanVo;
import cn.ondraw.system.domain.vo.SysUserVo;
import cn.ondraw.system.service.ISysModelService;
import cn.ondraw.system.service.ISysPackagePlanService;
import cn.ondraw.system.service.ISysUserService;
import cn.ondraw.system.util.DesensitizationUtil;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 系统模型
 *
 * @author Lion Li
 * @date 2024-04-04
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/system/model")
public class SysModelController extends BaseController {

    private final ISysModelService sysModelService;

    private final ISysPackagePlanService sysPackagePlanService;

    private final ISysUserService userService;

    /**
     * 查询系统模型列表 - 全部
     */
    @GetMapping("/list")
    public TableDataInfo<SysModelVo> list(SysModelBo bo, PageQuery pageQuery) {
        return sysModelService.queryPageList(bo, pageQuery);
    }

    /**
     * 查询系统模型列表
     */
    @GetMapping("/modelList")
    public R<List<SysModelVo>> modelList(SysModelBo bo) {
        // 设置模型显示状态
        bo.setModelShow("0");
        // 查询系统模型列表
        List<SysModelVo> sysModelVos = sysModelService.queryList(bo);
        // 创建系统套餐计划对象
        SysPackagePlanBo sysPackagePlanBo = new SysPackagePlanBo();

        // 判断用户是否登录
        if (StpUtil.isLogin()) {
            // 获取当前登录用户的ID
            Long userId = LoginHelper.getLoginUser().getUserId();
            // 根据用户ID查询用户信息
            SysUserVo sysUserVo = userService.selectUserById(userId);
            // 判断用户等级是否为"0"（例如：免费用户）
            if ("0".equals(sysUserVo.getUserGrade())){
                // 设置套餐计划名称为"Free"
                sysPackagePlanBo.setName("Free");
                // 查询免费用户的套餐计划详情
                SysPackagePlanVo sysPackagePlanVo = sysPackagePlanService.queryList(sysPackagePlanBo).get(0);
                // 将套餐计划的详细内容（字符串）转换为列表
                List<String> array = new ArrayList<>(Arrays.asList(sysPackagePlanVo.getPlanDetail().split(",")));
                // 移除不允许访问的模型
                sysModelVos.removeIf(model -> !array.contains(model.getModelName()));
            }
        }else {
            // 如果未登录，设置套餐计划名称为"Visitor"
            sysPackagePlanBo.setName("Visitor");
            // 查询访客的套餐计划详情
            SysPackagePlanVo sysPackagePlanVo = sysPackagePlanService.queryList(sysPackagePlanBo).get(0);
            // 将套餐计划的详细内容（字符串）转换为列表
            List<String> array = new ArrayList<>(Arrays.asList(sysPackagePlanVo.getPlanDetail().split(",")));
            // 移除不允许访问的模型
            sysModelVos.removeIf(model -> !array.contains(model.getModelName()));
        }

        // 对模型列表中的每个模型进行脱敏处理
        sysModelVos.stream().map(vo -> {
            // 对API主机地址进行脱敏处理
            String maskedApiHost = DesensitizationUtil.maskData(vo.getApiHost());
            // 对API密钥进行脱敏处理
            String maskedApiKey = DesensitizationUtil.maskData(vo.getApiKey());
            // 将脱敏后的数据设置回模型对象
            vo.setApiHost(maskedApiHost);
            vo.setApiKey(maskedApiKey);
            return vo;
        }).collect(Collectors.toList());

        // 返回处理后的系统模型列表
        return R.ok(sysModelVos);
    }

    /**
     * 导出系统模型列表
     */
    @Log(title = "系统模型", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(SysModelBo bo, HttpServletResponse response) {
        List<SysModelVo> list = sysModelService.queryList(bo);
        ExcelUtil.exportExcel(list, "系统模型", SysModelVo.class, response);
    }

    /**
     * 获取系统模型详细信息
     *
     * @param id 主键
     */
    @SaCheckPermission("system:model:query")
    @GetMapping("/{id}")
    public R<SysModelVo> getInfo(@NotNull(message = "主键不能为空")
                                     @PathVariable Long id) {
        return R.ok(sysModelService.queryById(id));
    }

    /**
     * 新增系统模型
     */
    @Log(title = "系统模型", businessType = BusinessType.INSERT)
    @PostMapping()
    public R<Void> add(@Validated(AddGroup.class) @RequestBody SysModelBo bo) {
        return toAjax(sysModelService.insertByBo(bo));
    }

    /**
     * 修改系统模型
     */
    @Log(title = "系统模型", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody SysModelBo bo) {
        return toAjax(sysModelService.updateByBo(bo));
    }

    /**
     * 删除系统模型
     *
     * @param ids 主键串
     */
    @SaCheckPermission("system:model:remove")
    @Log(title = "系统模型", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @PathVariable Long[] ids) {
        return toAjax(sysModelService.deleteWithValidByIds(List.of(ids), true));
    }
}
